// pages/goodsDetail/goodsDetail.js
import { goodsDateils, collectionProduct, deleteCollectionProduct, goodsComment, goodsCommentCount} from '../../api/url.js'
import { formatSku, formatTime } from '../../utils/util.js'
const app=getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showAttrModal:false,//是否显示属性模态框
    headerHeight:0,//导航栏高度
    goodsId:'',//商品id
    showModal:false,//是否显示sku模态框
    modalType:'product',//显示产品详情还是评价
    isCollected:false,//此商品是否被收藏
    page:1,//页码
    size:10,//每页数据数量
    loadOver:false,//评论是否加载完毕
    comments:[],//评论
    commentsCount:null,//评论数量
    currentCommentType:'all',//现在激活的评价类型
    isIPX:false,//是否是iPhoneX
  },
  /**
   * @method
   * @desc 预览图片
   */
  previewImgs(e){
    wx.previewImage({
      urls: e.currentTarget.dataset.imgs,
    })
  },
  /**
   * @method
   * @desc 切换评论类型
   */
  toggleCommentType(e){
    let that=this
    let temCurrentCommentType = e.currentTarget.dataset.comtype
    that.setData({
      currentCommentType:temCurrentCommentType,
      comments: [],
      page:1,
      loadOver:false
    })
    that.goodsComment(that.data.currentCommentType)
  },
  /**
   * @method
   * @desc 加载商品评论
   */
  goodsComment(score){
    let that=this
    let query=null
    if(score!='all'){
      query={
        fProductId: this.data.goodsId,
        page: this.data.page,
        size: this.data.size,
        fState: 'normal',
        fAvgScore:score
      }
    }else{
      query={
        fProductId: this.data.goodsId,
        page: this.data.page,
        size: this.data.size,
        fState: 'normal'
      }
    }
    wx.request({
      url: goodsComment,
      data:query,
      success(res){
        if(res.data.code===0){
          that.setData({
            page:that.data.page+1
          })
          let temComments=res.data.response.cont.list
          if(temComments.length<(that.data.size-1)){
            that.setData({
              loadOver:true
            })
          }
          temComments.forEach(val=>{
            if (typeof val.fTime == 'number') {
              val.time = formatTime(val.fTime)
            } else {
              val.time = val.fTime
            }
            val.imgs = val.imgList.map(val1=>{
              return app.globalData.imageBaseUrl + val1.fImage
            })
          })
          that.setData({
            comments: that.data.comments.concat(temComments) 
          })
        }else{
          wx.showToast({
            title: '加载商品评论异常',
            icon:'none'
          })
        }
      },
      fail(){
        wx.showToast({
          title: '加载商品评论失败',
          icon:'none'
        })
      }
    })
  },
  /**
   * @method
   * @desc 跳转优惠券列表页
   */
  goCoupons(){
    wx.navigateTo({
      url: '/pages/coupons/coupons?fromPage=goodsDetail',
    })
  },
  /**
   * @method
   * @desc 加顶部padding
   */
  setPadding(e) {
    let that = this
    that.setData({
      headerHeight: e.detail
    })
  },
  /**
   * @method
   * @desc 跳转购物车
   */
  tapToShopCart(){
    wx.switchTab({
      url: '/pages/shopCart/shopCart',
    })
  },


  /**
   * @method
   * @desc 打开关闭属性模态框
   */
  toggleAttrModal() {
    let that = this
    that.setData({
      showAttrModal: !that.data.showAttrModal
    })
  },

  /**
   * @method
   * @desc 切换信息模态框
   */
  toggleModal(e){
    let that=this
    that.setData({
      modalType:e.currentTarget.dataset.type
    })
  },

  /**
   * @method 
   * @desc 判断是否被收藏
   * @param goodsId
   */
  isCollected(goodsId){
    let that=this
    let temColStr = ',' + app.globalData.collections.join(',')+','
    that.setData({
      isCollected: temColStr.indexOf(',' + goodsId + ',') == -1 ? false : true
    })
    return temColStr.indexOf(',' + goodsId + ',') == -1 ? false : true
  },
  /**
   * @method
   * @desc 收藏商品
   */
  collect(){
    let that=this
    if(that.isCollected(that.data.goodsId)){
      //取消收藏
      wx.showLoading({
        title: '取消收藏',
        mask:true
      })
      wx.request({
        url: deleteCollectionProduct,
        data:{
          fCollectionId: that.data.goodsId,
          fUserId: app.globalData.userInfo.id,
          token: wx.getStorageSync('token'),
          loginName: app.globalData.userInfo.loginname
        },
        success(res){
          wx.hideLoading()
          if(res.data.code===0){
            wx.showToast({
              title: '取消收藏',
              icon:'none'
            })
            app.globalData.collections = app.globalData.collections.filter(val=>{
              val!=that.data.goodsId
            })
            that.isCollected(that.data.goodsId)
          }
        },
        fail(res){
          wx.showToast({
            title: '取消收藏异常',
            icon:'none'
          })
          wx.hideLoading()
        }
      })
    }else{
      //收藏
      wx.showLoading({
        title: '收藏中',
        mask:true
      })
      wx.request({
        url: collectionProduct,
        data:{
          fCollectionId:that.data.goodsId,
          fUserId:app.globalData.userInfo.id,
          fType:1,
          State:0,
          token:wx.getStorageSync('token'),
          loginName: app.globalData.userInfo.loginname
        },
        success(res){
          wx.hideLoading()
          if(res.data.code===0){
            wx.showToast({
              title: '收藏成功',
              icon:'none'
            })
            app.globalData.collections.push(that.data.goodsId)
            that.isCollected(that.data.goodsId)
          }else{
            wx.showToast({
              title: '收藏异常',
              icon:'none'
            })
          }
        },
        fail(){
          wx.hideLoading()
          wx.showToast({
            title: '收藏失败',
            icon:'none'
          })
        }
      })
    }
  },



  /**
   * @method
   * @desc 关闭sku模态框
   */
  closeModal(){
    let that=this
    that.setData({
      showModal:false
    })
  },
  /**
   * @method
   * @desc 点击加入购物车和立即购买
   */
  tapOpenModal(e){
    let that=this
    let total=e.currentTarget.dataset.total
    if(total>0){
      that.setData({
        showModal: true
      })
    }else{
      wx.showToast({
        title: '库存不足',
        icon:'none'
      })
    }
    
  },
  /**
   * @method
   * @desc 加载商品详情
   * @param goodsId
   */
  loadGoodsDetail(id){
    let that=this
    wx.showLoading({
      title: '加载中',
      mask:true
    })
    wx.request({
      url: goodsDateils,
      data:{
        id
      },
      success(res){
        wx.hideLoading()
        if(res.data.code===0){
          let temDetail = res.data.response.cont
          temDetail.productImgList.forEach(val=>{
            val.img = app.globalData.imageBaseUrl + val.fImage
          })
          temDetail.priceTxt = temDetail.fFixedPrice.toFixed(2)
          if (temDetail.skuAndPropAndPropValList && temDetail.skuAndPropAndPropValList.length>0){
            temDetail.skuData = formatSku(temDetail.skuAndPropAndPropValList,that.data.goodsId)
            temDetail.fTotalCount = temDetail.skuAndPropAndPropValList[0].fStock
          }else{
            temDetail.skuData=null
          }
          if (temDetail.skuData > 0) {
            temDetail.skuPriTxt = temDetail.skuData.priceMap[0].price
          } else {
            temDetail.skuPriTxt = temDetail.priceTxt
          }
          that.setData({
            detail:temDetail
          })
        }else{
          wx.showToast({
            title: '加载商品详情异常',
            icon:'none'
          })
        }
      },
      fail(){
        wx.hideLoading()
        wx.showToast({
          title: '加载商品失败',
          icon:'none'
        })
      }
    })
  },
  /**
   * @method
   * @desc 加载评论数量
   */
  loadCommentsCounts(){
    let that=this
    wx.request({
      url: goodsCommentCount ,
      data:{
        fProductId:that.data.goodsId
      },
      success(res){
        if(res.data.code===0){
          that.setData({
            commentsCount:res.data.response.cont
          })
        }else{
          wx.showToast({
            title: '查询商品评价数量异常',
            icon:'none'
          })
        }
      },
      fail(){
        wx.showToast({
          title: '查询商品评价数量失败',
          icon:'none'
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that=this
    that.setData({
      goodsId:options.id,
      isIPX: app.globalData.isIPX
    })
    that.loadGoodsDetail(that.data.goodsId)
    that.isCollected(that.data.goodsId)
    that.goodsComment(that.data.currentCommentType)
    that.loadCommentsCounts()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    let that=this
    that.setData({
      showAttrModal: false,//是否显示属性模态框
      showModal: false,//是否显示sku模态框
      modalType: 'product',//显示产品详情还是评价
      page: 1,//页码
      loadOver: false,//评论是否加载完毕
      comments: [],//评论
      commentsCount: null,//评论数量
      currentCommentType: 'all',//现在激活的评价类型
    })
    that.loadGoodsDetail(that.data.goodsId)
    that.isCollected(that.data.goodsId)
    that.goodsComment(that.data.currentCommentType)
    that.loadCommentsCounts()
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let that=this
    if (that.data.modalType === "evaluation"){
      if (!that.data.loadOver) {
        that.goodsComment(that.data.currentCommentType)
      } else {
        wx.showToast({
          title: '到底啦',
          icon: 'none'
        })
      }
    }
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  }
})